package cq.zhcqk.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.dou361.dialogui.DialogUIUtils;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonParser;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.apache.http.Header;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cq.zhcqk.R;
import cq.zhcqk.alipay.PayResult;
import cq.zhcqk.axst.entity.Cart;
import cq.zhcqk.base.BaseActivity;
import cq.zhcqk.util.Common;
import cq.zhcqk.util.GsonUtil;
import cq.zhcqk.util.JsUtil;
import cq.zhcqk.util.SpUtil;
import cq.zhcqk.util.StringUtil;
import cq.zhcqk.util.ToastUtil;
import cq.zhcqk.util.WebViewHeader;
import cq.zhcqk.util.wxapi.Constants;
import cq.zhcqk.util.x5.X5WebView;

/**
 * Created by zhangle on 2018/3/22.
 */
public class AXST_WebActivity extends BaseActivity implements View.OnClickListener{

    private X5WebView tc_webview;
    private Context context;
    private TextView header_back_text;

    String token = null;

    private IWXAPI api;
    private static final int SDK_PAY_FLAG = 1;

    @Override
    protected void initView() {
        setContentView(R.layout.activity_axst_weblay);
        tc_webview = (X5WebView) findViewById(R.id.tc_webview);
        context = this;
        mSharedPreferences = SpUtil.getSpBykey(context, SpUtil.TOKEN);
        api = WXAPIFactory.createWXAPI(context, null);
    }

    @Override
    protected void initData() {
        token = mSharedPreferences.getString("token",null);
        initBack();
        webSet();
    }

    @Override
    protected void onResume() {
        super.onResume();
        WebViewHeader.setHeaderTokenAndLoadX5(tc_webview,"http://106.14.202.180:443/api/relation/h5list",token);
    }

    private void initBack(){
        ImageView back = (ImageView) findViewById(R.id.header_back);
        TextView title = (TextView) findViewById(R.id.header_text);
        title.setText("爱心食堂");
        back.setOnClickListener(this);
        header_back_text = (TextView) findViewById(R.id.header_back_text);
        header_back_text.setOnClickListener(this);
    }

    public void webSet(){
        if(tc_webview != null)
        {
            com.tencent.smtt.sdk.WebSettings settings = tc_webview.getSettings();
            settings.setJavaScriptEnabled(true);
            settings.setBuiltInZoomControls(true);
            settings.setLoadWithOverviewMode(true);
            settings.setUseWideViewPort(true);
            settings.setDatabaseEnabled(true);
            settings.setBuiltInZoomControls(false);
            settings.setSupportZoom(false);
            settings.setDisplayZoomControls(false);
            ButtonClick click = new ButtonClick();
            //这里添加JS的交互事件，这样H5就可以调用原生的代码
            tc_webview.addJavascriptInterface(click,click.toString());
            tc_webview.setWebViewClient(new com.tencent.smtt.sdk.WebViewClient()
            {
                @Override
                public void onPageFinished(com.tencent.smtt.sdk.WebView webView, String s) {
                    super.onPageFinished(webView, s);
                    DialogUIUtils.dismiss(buildBean);
                }

                @Override
                public void onPageStarted(com.tencent.smtt.sdk.WebView webView, String s, Bitmap bitmap) {
                    super.onPageStarted(webView, s, bitmap);
                    buildBean.show();
                }
            });
        }
    }

    /**
     * H5页面按钮点击触发事件
     */
    class ButtonClick{

        //这是 button.click0() 的触发事件
        //H5调用方法：javascript:button.click0()
        @JavascriptInterface
        public void appLogin(){
            context.startActivity(new Intent(context, LoginActivity.class));
            overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
        }

        @JavascriptInterface
        public void appPay(String data1,String data2,String data3){
            pay(data3,data2,data1);
        }

        //这是 button.click0() 的触发事件，可以传递待参数
        //H5调用方法：javascript:button.click0('参数1','参数2')
        @JavascriptInterface
        public void click0(String data1,String data2){
            show(data1,data2);
        }


        @JavascriptInterface  //必须添加，这样才可以标志这个类的名称是 button
        public String toString(){
            return "button";
        }

        private void show(String title,String data){
            ToastUtil.showToast(context,title);
        }
    }

    private void pay(final String payType, String priceSum, String datas){
        RequestParams params = new RequestParams();
        params.add("type",payType);
        params.add("money",priceSum);
        Gson gson = new Gson();
        List<Map<String,Object>> map = gson.fromJson(datas,ArrayList.class);
        params.add("dishesDetailJson",datas);
        String url = "";
        url = Common.URL+Common.DISHESORDER;
        System.out.println(params);
        buildBean.show();
        httpClient.post(url,params,new JsonHttpResponseHandler(){
            @Override
            public void onSuccess(int statusCode, Header[] headers,
                                  JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                System.out.println("onSuccess："+response);
                Map<String, Object> map = GsonUtil.GsonToMaps(response+"");
                if(StringUtil.stringToInt(map.get("code")+"") != 0){
                    Toast.makeText(context,"获取失败，请稍后再试",Toast.LENGTH_SHORT).show();
                    return;
                }
                if(map.get("data") == null || "".equals(map.get("data")+"")){
                    Toast.makeText(context,"支付失败，请稍后再试",Toast.LENGTH_SHORT).show();
                }else{
                    if("1".equals(payType)){
                        payV2(map.get("data")+"");
                    }else if("2".equals(payType)){
                        wxPay((Map<String, Object>)map.get("data"));
                    }
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers,
                                  Throwable throwable, JSONObject errorResponse) {
                super.onFailure(statusCode, headers, throwable,
                        errorResponse);
                System.out.println("errorResponse："+errorResponse);
                Toast.makeText(context,"获取失败，请稍后再试",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                System.out.println("responseString："+responseString);
                Toast.makeText(context,"获取失败，请稍后再试",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                DialogUIUtils.dismiss(buildBean);
            }
        });
    }

    /**
     * 发起支付宝支付
     * @param orderInfo
     */
    public void payV2(final String orderInfo) {
        if (StringUtil.isNull(orderInfo)){
            Toast.makeText(context, "获取订单数据失败", Toast.LENGTH_SHORT).show();
            return;
        }

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(mActivity);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(context, "支付成功", Toast.LENGTH_SHORT).show();
//                        DialogUIUtils.dismiss(dialog);
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(context, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
                default:
                    break;
            }
        }
    };

    /**
     * 微信支付
     * @param orderInfo
     */
    private void wxPay(Map<String, Object> orderInfo){
        PayReq req = new PayReq();
//        req.appId			= orderInfo.get("appid")+"";
        req.appId			= Constants.APP_ID;
        req.partnerId		= orderInfo.get("partnerid")+"";
        req.prepayId		= orderInfo.get("prepayid")+"";
        req.nonceStr		= orderInfo.get("noncestr")+"";
        req.timeStamp		= StringUtil.stringToInt(orderInfo.get("timestamp")+"")+"";
        req.packageValue	= orderInfo.get("package")+"";
        req.sign			= orderInfo.get("sign")+"";
        // 将该app注册到微信
        api.registerApp(Constants.APP_ID);
//        IWXMsg.registerApp;
        api.sendReq(req);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.header_back:
                if (tc_webview.canGoBack())
                {
                    tc_webview.goBack(); //goBack()表示返回WebView的上一页面
                }else
                {
                    finish();
                }
                break;
            case R.id.header_back_text:
                finish();
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) ) {
            if (tc_webview.canGoBack())
            {
                tc_webview.goBack(); //goBack()表示返回WebView的上一页面
                return true;
            }else
            {
                finish();
                return true;
            }

        }
        return false;
    }
}
